<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2018/2/7
 * Time: 上午8:18
 * 小程序设置
 */

namespace app\macht\controller;


use app\common\controller\AdminBase;
use app\common\controller\TestBase;
use app\common\model\Agent;
use app\common\model\CardMember;
use app\common\model\Merchant;
use app\common\model\Momerchant;
use app\common\model\System;
use app\common\model\WxOpen;

use app\common\model\XcxInfo;
use app\common\model\XcxSet;
use app\common\model\Yuyue;
use think\Controller;
use think\Session;
use Wechat\Wxobjopen;

class Microprogram extends MachBase
{
    //小程序管理
    public function index(){
        return $this->fetch();
    }


    //设置服务器域名
    public function set_xcx_domain()
    {
        $options = $this->options2();

        $wxObj = new Wxobjopen($options);
        $mid=Session::get('login_top_mid');
        $Merchant=new Merchant();
        $Agent=new Agent();
        $agent=$Merchant->where(array('top_mid'=>$mid))->value('agent');
        $info=$Agent->where(array('id'=>$agent))->find();
        $param['action'] = "add";
        $param['requestdomain'] = $info['requestdomain'];
        $param['wsrequestdomain'] = $info['wsrequestdomain'];
        $param['uploaddomain'] = $info['uploaddomain'];
        $param['downloaddomain'] = $info['downloaddomain'];
        if (request()->isAjax()) {
            $errcode = $wxObj->set_xcx_domain($param);
            if ($errcode['errcode'] == 0) {
                $data['code'] = 0;
                $data['message'] = "操作成功";
            } else {
                $data['code'] = $errcode['errcode'];
                $data['message'] = $errcode['errmsg'];
            }
            return json($data);
        } else {
            $Wxopen = new WxOpen();
            $open = $Wxopen->where(['authorizer_appid' => $options['authorizer_appid']])->value('xcx_appsecret');
            $open2 = $Wxopen->where(['authorizer_appid' => $options['authorizer_appid']])->value('xcx_yy_tpl');
            $this->assign('open', $open);
            $this->assign('open2', $open2);
            $this->assign('info', $info);
            return $this->fetch();
        }

    }


    //设置业务域名
    public function setwebviewdomain()
    {
        if (request()->isAjax()) {
            $options = $this->options2();
            $wxObj = new Wxobjopen($options);
            $mid=Session::get('login_top_mid');
            $Merchant=new Merchant();
            $Agent=new Agent();
            $agent=$Merchant->where(array('top_mid'=>$mid))->value('agent');
            $info=$Agent->where(array('id'=>$agent))->find();
            $param['action'] = "add";
            $param['webviewdomain'] = $info["webviewdomain"];
            $errcode = $wxObj->set_xcx_webviewdomain($param);
            if ($errcode['errcode'] == 0) {
                $data['code'] = 0;
                $data['message'] = "操作成功";
            } else {
                $data['code'] = $errcode['errcode'];
                $data['message'] = $errcode['errmsg'];
            }
            return json($data);
        }
    }

    //获取体验二维码
    public function getqrcode()
    {
        if (request()->isAjax()) {
            $options = $this->options2();
//            file_put_contents('/data2/html/payos/fireuser.txt', 'xcx-1' . json_encode($options), FILE_APPEND);
            $wxObj = new Wxobjopen($options);
            $s = $wxObj->xcx_getqrcode();
//            file_put_contents('/data2/html/payos/fireuser.txt', 'xcx-2' . json_encode($s), FILE_APPEND);
            return $s;

        }

    }

    //获取小程序可选目录
    public function get_category()
    {
        $options = $this->options2();

        $wxObj = new Wxobjopen($options);
        $ss = $wxObj->xcx_getcategory();

        if (isset($ss['category_list'][0])) {
            $data['first_class'] = $ss['category_list'][0]['first_class'];
            $data['second_class'] = $ss['category_list'][0]['second_class'];
            $data['first_id'] = $ss['category_list'][0]['first_id'];
            $data['second_id'] = $ss['category_list'][0]['second_id'];
        } else {
            $data['first_class'] = "";
            $data['second_class'] = "";
            $data['first_id'] = "";
            $data['second_id'] = "";
        }
        return $data;

    }

    //获取小程序的第三方提交代码的页面配置
    public function get_page()
    {
        $options = $this->options2();

        $wxObj = new Wxobjopen($options);
        $ss = $wxObj->xcx_getpage();
        return $ss['page_list'][0];

    }

    //门店操作
    public function set_prostore()
    {
        if (request()->isPost()) {
            $arr = request()->post();
//            var_dump($arr);
//            exit();
            $data['pictures'] = $arr['store_pic'];
            $Momerchant = new Momerchant();
            $top_mid = Session::get('login_top_mid');
            $res = $Momerchant->save($data, ['id' => $top_mid]);
            if ($res) {
                $this->success('上传成功', 'microprogram/set_prostore');
            } else {
                $this->error('上传失败', 'microprogram/set_prostore');
            }
        } else {
            $Momerchant = new Momerchant();
            $top_mid = Session::get('login_top_mid');
            $info = $Momerchant->where(['id' => $top_mid])->find();
            $pictures = $info['pictures'];
//            var_dump($pictures);
            $this->assign("pictures", $pictures);
            return $this->fetch();
        }
    }

    //绑定体验者
    public function bind_tester()
    {
        if (request()->isAjax()) {
            $options = $this->options2();
            $wxObj = new Wxobjopen($options);
            $param['wechatid'] = request()->post('wechatid');
            $errcode = $wxObj->xcx_bind_tester($param);//绑定体验者
            if ($errcode['errcode'] == 0) {
                $data['code'] = 0;
                $data['message'] = "操作成功";
            } else {
                $data['code'] = $errcode['errcode'];
                $data['message'] = $errcode['errmsg'];
            }
            return json($data);
        } else {
            return $this->fetch();
        }
    }

    //解绑体验者
    public function unbindtester()
    {
        if (request()->isAjax()) {
            $options = $this->options2();
            $wxObj = new Wxobjopen($options);
            $param['wechatid'] = request()->post('wechatid');
            $errcode = $wxObj->xcx_unbind_tester($param);//解绑体验者
            if ($errcode['errcode'] == 0) {
                $data['code'] = 0;
                $data['message'] = "操作成功";
            } else {
                $data['code'] = $errcode['errcode'];
                $data['message'] = $errcode['errmsg'];
            }
            return json($data);
        }
    }

    public function get_card_id()
    {
        $mid = Session::get('login_top_mid');
        $CardMember = new CardMember();
        $card_id = $CardMember->where(['top_mid' => $mid])->value('card_id');

        return $card_id;
    }

    //发布小程序
    public function sub_program()
    {
        if (request()->isAjax()) {
            $options = $this->options2();
            $wxObj = new Wxobjopen($options);
            $templateId = request()->post('template_id');
            $version = request()->post('user_version');
            $descript = request()->post('user_desc');
            $appId = request()->post('extAppid');

            $extJson = array(
                'extAppid' => $appId,
                'ext' => array(
                    "attr" => array(
                        'weburl' => request()->post('weburl'),
                        'merchid' => request()->post('merchid'),
                        'siteurl' => request()->post('siteurl'),
                        'card_id' =>request()->post('card_id'),

                    )
                )
            );
            $params = array(
                'template_id' => $templateId,
                'user_version' => $version,
                'user_desc' => $descript,
                'ext_json' => json_encode($extJson, JSON_UNESCAPED_UNICODE)
            );

            $errcode = $wxObj->xcx_commit($params);//发布小程序
            if ($errcode['errcode'] == 0) {
                $data['code'] = 0;
                $data['message'] = "操作成功";
            } else {
                $data['code'] = $errcode['errcode'];
                $data['message'] = $errcode['errmsg'];
            }
            return json($data);

        } else {
            $options = $this->options2();
            $wxObj = new Wxobjopen($options);
            $xcxget = $wxObj->get_xcx_search();
            if ($xcxget['errcode'] == 0) {
                $xcxstatu = $xcxget['status'];

            } else {
                $xcxstatu = "";

            }
            $top_mid = Session::get('login_top_mid');
            $Momerchant = new Momerchant();
            $WxOpen = new WxOpen();
            $wx_open_id = $Momerchant->where('id', $top_mid)->value('wx_open_id_xcx');

            $users = $WxOpen->where(['id' => $wx_open_id])->find();
            $XcxSet = new XcxSet();
            $xcxset = $XcxSet->order('id desc')->find();
            $merchid = Session::get('login_top_mid');
            $map['mid'] = $merchid;
            $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
            $siteurl = $http_type . $_SERVER['HTTP_HOST'];
            $card_id=$this->get_card_id();
            $this->assign('card_id',$card_id);
            $this->assign('siteurl', $siteurl);
            $xcxinfo = XcxInfo::where($map)->order('id desc')->select();;
            $this->assign('xcxinfo', $xcxinfo);
            $this->assign('xcxstatu', $xcxstatu);
            $this->assign('merchid', $merchid);
            $this->assign('xcxset', $xcxset);
            $this->assign('wx_open', $users);
            return $this->fetch();
        }


    }

    //提交审核
    public function sub_program_sh()
    {
        if (request()->isAjax()) {
            $datac = $this->get_category();
            if ($datac['first_class'] !== "" || $datac['second_class'] !== "") {

                $options = $this->options2();
                $wxObj = new Wxobjopen($options);
                $param['address'] = $this->get_page();
                $param['tag'] = request()->post('tag');;

                if ($datac['first_class'] !== "") {
                    $param['first_class'] = $datac['first_class'];
                    $param['first_id'] = $datac['first_id'];
                }

                if ($datac['second_class'] !== "") {
                    $param['second_class'] = $datac['second_class'];
                    $param['second_id'] = $datac['second_id'];
                }

                $param['title'] = "首页";

                $params['item_list'][] = $param;

                $errcode = $wxObj->xcx_submitaudit($params);//提交审核
                if ($errcode['errcode'] == 0) {
                    $data['code'] = 0;
                    $data['message'] = "操作成功";
                    $sdata['mid'] = Session::get('login_top_mid');
                    $sdata['auditid'] = $errcode['auditid'];
                    $sdata['addtime'] = time();
                    $sdata['status'] = 2;
                    $XcxInfo = new XcxInfo();
                    $XcxInfo->save($sdata);

                } else {
                    $data['code'] = $errcode['errcode'];
                    $data['message'] = $errcode['errmsg'];
                }
            } else {
                $data['code'] = 9999;
                $data['message'] = "没有设置所属行业，请先至公众平台完善小程序信息";
            }
            return json($data);

        }


    }

    public function xcx_uncode()
    {
        if (request()->isAjax()) {
            $options = $this->options2();
            $wxObj = new Wxobjopen($options);
            $ss = $wxObj->get_xcx_uncode();
            if ($ss['errcode'] == 0) {
                $data['code'] = 0;
                $data['message'] = "操作成功";
            } else {
                $data['code'] = $ss['errcode'];
                $data['message'] = $ss['errmsg'];
            }
            return json($data);
        }
    }

    public function tpl_ku()
    {

        $options = $this->options2();
        $wxObj = new Wxobjopen($options);
        $sys = System::find();

        $param['id'] = $sys['xcx_yy_tpl'];

        $ss = $wxObj->xcx_tpl_ku($param);
        var_dump($ss);

    }

    public function tpl_add()
    {
        if (request()->isAjax()) {
            $options = $this->options2();
            $wxObj = new Wxobjopen($options);
            $sys = System::find();
            $param['id'] = $sys['xcx_yy_tpl'];
            $param['keyword_id_list'] = [1, 2, 10, 4, 11];
            $ss = $wxObj->xcx_tpl_add($param);
            if ($ss['errcode'] == 0) {
                $top_mid = Session::get('login_top_mid');
                $Momerchant = new Momerchant();

                $WxOpen = new WxOpen();
                $wx_open_id = $Momerchant->where('id', $top_mid)->value('wx_open_id_xcx');
                $data['xcx_yy_tpl'] = $ss['template_id'];
                $WxOpen->save($data, ['id' => $wx_open_id]);
                $sdata['code'] = 0;
                $sdata['message'] = "设置成功";
            } else {
                $sdata['code'] = $ss['errcode'];
                $sdata['message'] = $ss['errmsg'];
            }
            return json($sdata);
        }
    }

    public function xcx_getauditstatus()
    {
        if (request()->isAjax()) {
            $options = $this->options2();
            $wxObj = new Wxobjopen($options);
//        $params["auditid"] = 420527434;
            $params["auditid"] = request()->post('auditid');
            $errcode = $wxObj->xcx_getauditstatus($params);
            $XcxInfo = new XcxInfo();
            if ($errcode['errcode'] == 0) {
                if ($errcode['status'] == 2) {
                    $data['code'] = 2;
                    $data['message'] = "当前小程序正在审核中";

                } elseif ($errcode['status'] == 1) {
                    $XcxInfo->save(['status' => 1, 'shtime' => time(), 'reason' => $errcode['reason']], ['auditid' => $params["auditid"]]);
                    $data['code'] = 1;
                    $data['message'] = "审核失败  " . $errcode['reason'];
                } elseif ($errcode['status'] == 0) {
                    $XcxInfo->save(['status' => 0, 'shtime' => time(), 'reason' => ''], ['auditid' => $params["auditid"]]);
                    $data['code'] = 0;
                    $data['message'] = "当前小程序审核成功";
                }
            }
            return json($data);

        }

    }

    public function setappsecret()
    {
        if (request()->isAjax()) {
            $option = $this->options2();
            $data['xcx_appsecret'] = request()->post('xcx_appsecret');
            $map['authorizer_appid'] = $option['authorizer_appid'];
            $Wxopen = new WxOpen();
            $add = $Wxopen->save($data, $map);
            if ($add) {
                $data['code'] = 0;
                $data['message'] = "操作成功";
            } else {
                $data['code'] = 1;
                $data['message'] = "操作失败";
            }
            return json($data);

        }


    }

    public function yylist()
    {
        $request = request();
        $p_data = $request->get();
        //搜索
        unset($p_data['page']);
        if ($p_data) {
            if ($p_data['starttime'] !== '') {
                $starttime = strtotime($p_data['starttime']);
            } else {
                $starttime = 0;
            }
            if ($p_data['endtime'] !== '') {
                $endtime = strtotime($p_data['endtime']) + 86400;
            } else {
                $endtime = strtotime(date('Y-m-d H:i:s'));
            }
            if ($p_data['merchname'] !== "") {
                $map['merchname'] = $p_data['merchname'];
            }
            if ($p_data['xingming'] !== "") {
                $map['xingming'] = $p_data['xingming'];
            }
            if ($p_data['tel'] !== "") {
                $map['tel'] = $p_data['tel'];
            }
            $map['addtime'] = array('between', '' . $starttime . ',' . $endtime . '');


        } else {
            $starttime = 0;
            $endtime = strtotime(date('Y-m-d 23:59:59'));
            $map['addtime'] = array('between', '' . $starttime . ',' . $endtime . '');
            $p_data['starttime'] = "";
            $p_data['endtime'] = "";
            $p_data['merchname'] = '';
            $p_data['xingming'] = '';
            $p_data['tel'] = '';

        }
        $map['merchid'] = Session::get('login_top_mid');
        $Yy = new Yuyue();
        $list = $Yy->where($map)->order('id desc')->paginate(10);
        $maa['top_mid'] = Session::get('login_top_mid');
        $Merchant = new Merchant();
        $machlist = $Merchant->where($maa)->select();
        $p_data['merchname'] = 1;
        $this->assign('machlist', $machlist);
        $this->assign('p_data', $p_data);
        $this->assign('list', $list);
        return $this->fetch();
    }

    public function set_xcx_search()
    {
        if (request()->isAjax()) {
            $options = $this->options2();
            $wxObj = new Wxobjopen($options);
            // "status":0, //1表示不可搜索，0表示可搜索
            $param['status'] = request()->post('status');
            $errcode = $wxObj->set_xcx_search($param);

            if ($errcode['errcode'] == 0) {
                $data['code'] = 0;
                $data['message'] = "操作成功";
            } else {
                $data['code'] = $errcode['errcode'];
                $data['message'] = $errcode['errmsg'];
            }
            return json($data);

        }

    }

    public function xcx_release()
    {
        if (request()->isAjax()) {
            $options = $this->options2();
            $wxObj = new Wxobjopen($options);
            // "status":0, //1表示不可搜索，0表示可搜索
            $param = [];;
            $errcode = $wxObj->xcx_release($param);

            if ($errcode['errcode'] == 0) {
                $data['code'] = 0;
                $data['message'] = "操作成功";
            } else {
                $data['code'] = $errcode['errcode'];
                $data['message'] = $errcode['errmsg'];
            }
            return json($data);

        }
    }

    public function options2()
    {

        $top_mid = Session::get('login_top_mid');
        $Momerchant = new Momerchant();
        $System = new System();
        $WxOpen = new WxOpen();
        $Agent=new Agent();

        $wx_open_id = $Momerchant->where('id', $top_mid)->value('wx_open_id_xcx');
        $agent_id = $Momerchant->where('id', $top_mid)->value('agent');
        $users = $WxOpen->where(['id' => $wx_open_id])->find();
        $config=$Agent->where(array('id'=>$agent_id))->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }
}